// axios
import axios from 'axios'
import {Loading, Message} from 'element-ui'
import utils from "./utils.js";

let loadingInstance = null // 加载全局的loading
export const baseUrl = 'http://rome.apibe.com:31312'
// export const baseUrl = 'http://apibe.top:2288'

const defaultInstance = axios.create({
    timeout: 10000,
    baseURL: baseUrl
})
const instance = axios.create({
    timeout: 10000,
    baseURL: baseUrl
})

instance.defaults.headers.post['Content-Type'] = 'application/json'
let httpCode = {
    400: '请求参数错误',
    401: '权限不足, 请重新登录',
    403: '服务器拒绝本次访问',
    404: '请求资源未找到',
    500: '内部服务器错误',
    501: '服务器不支持该请求中使用的方法',
    502: '网关错误',
    504: '网关超时'
}
/**
 * 添加请求拦截器
 */
instance.interceptors.request.use(config => {
    loadingInstance = Loading.service({
        spinner: 'fa fa-spinner fa-spin fa-3x fa-fw',
        text: '拼命加载中...'
    })
    if (config.method === 'get') { // 添加时间戳参数，防止浏览器（IE）对get请求的缓存
        config.params = { // 添加时间戳参数，防止浏览器（IE）对get请求的缓存
            ...config.params,
            t: new Date().getTime()
        }
    }
    return config
}, error => {
    Message({
        message: 'request err',
        type: 'error'
    })
    return Promise.reject(error)
})
/**
 * 添加响应拦截器
 */
instance.interceptors.response.use(response => {
    loadingInstance.close()
    return Promise.resolve(response)
}, error => {
    loadingInstance.close()
    if (error.response) {
        let tips = error.response.status in httpCode ? httpCode[error.response.status] : error.response.data.msg
        Message({
            message: tips,
            type: 'error'
        })
        if (error.response.status === 401) {    // token或者登陆失效情况下跳转到登录页面，根据实际情况，在这里可以根据不同的响应错误结果，做对应的事。这里我以401判断为例
            this.$router.push({
                path: `/login`
            })
        }
        return Promise.reject(error)
    } else {
        Message({
            message: '请求超时, 请刷新重试',
            type: 'error'
        })
        return Promise.reject(new Error('请求超时, 请刷新重试'))
    }
})
/**
 * 统一封装post请求
 */
export const post = (url, data, config = {}, auth = false, encrypt = false) => {
    let headers = {}
    if (auth) {
        headers['Authorization'] = 'APIBE t-' + sessionStorage.getItem(utils.constPool.TOKEN) || ''
    }
    if (encrypt) {
        data = utils.encrypt(data)
    }
    // todo 测试：未加密
    headers['debug'] = 'APIBE'
    console.log(url)
    return instance({
        method: 'post',
        url,
        headers,
        data,
        ...config
    }).then(response => {
        return Promise.resolve(response)
    }).catch(error => {
        return Promise.reject(error)
    })

}
/**
 * 统一封装get请求
 */
export const get = (url, headers, params, config = {}, auth = false) => {
    if (auth) {
        headers['Authorization'] = 'APIBE t-' + sessionStorage.getItem('token') || ''
    }
    return instance({
        method: 'get',
        url,
        headers,
        params,
        ...config
    }).then(response => {
        return Promise.resolve(response)
    }).catch(error => {
        return Promise.reject(error)
    })
}

export const defaultPost = (url, data, config = {}, auth = false, encrypt = false) => {
    let headers = {}
    if (auth) {
        headers['Authorization'] = 'APIBE t-' + sessionStorage.getItem(utils.constPool.TOKEN) || ''
    }
    if (encrypt) {
        data = utils.encrypt(data)
    }
    // todo 测试：未加密
    headers['debug'] = 'APIBE'
    return defaultInstance({
        method: 'post',
        url,
        headers,
        data,
        ...config
    }).then(response => {
        return Promise.resolve(response)
    }).catch(error => {
        return Promise.reject(error.response)
    })
}
